<script setup lang="ts">
import vueTitle from '../components/title.vue'
import { appWindow,LogicalSize } from '@tauri-apps/api/window'
import { ref,reactive, onMounted } from 'vue'

//#region 窗口按钮
const miniWindow = function(){
    appWindow.minimize();
}

const maxWindow = function(){
    appWindow.toggleMaximize();
}

const closeWindow = function(){
    appWindow.hide();
    // localStorage.clear();
}
//#endregion

//#region exec程序执行
import { Command,open } from '@tauri-apps/api/shell'
import { convertFileSrc } from '@tauri-apps/api/tauri';
const execCommand =async function(exec:string){
    // await open('F:/note/public/icon/max.png','open')
    // await open("C:/Users/Angel/Pictures/a.jpg")
    await open(exec)
}

//#endregion

//#region 拖拽代码
import { lnk } from "../types";
const lnkarr:lnk[] = reactive([]);
// 开始拖动
const dragstart =  function(event:DragEvent,index:number,item:lnk){
    console.log('start',index)
    delbool.value = true
    event.dataTransfer?.setData('index',index.toString());
    event.dataTransfer?.setData('lnk',JSON.stringify(item));
}

// 阻止默认事件
const dragover = function(event:DragEvent){
    event.preventDefault();
}

// 放置
const drop = function(event:DragEvent,index:number){
    event.preventDefault();
    let str:any = event.dataTransfer?.getData('index');
    let dragIndex = parseInt(str);
    if(dragIndex !== index){
        let dragData = lnkarr[dragIndex];
        lnkarr[dragIndex] = lnkarr[index];
        lnkarr[index] = dragData;
    }
    delbool.value = false
}

// 删除快捷
const delbool = ref<boolean>(false);
const dragdelete = function(event:DragEvent){
    let str:any = event.dataTransfer?.getData('index');
    let dragIndex = parseInt(str);
    lnkarr.splice(dragIndex,1);
    savelnk();
}

//#endregion

//#region 添加新lnk
const newlnk = ref<string>('');
const newicon = ref<string>('');
const newprogram = ref<string>('');
const visible = ref<boolean>(false)

// 显示表单
const add = function(){
    visible.value = true
}

// 选择添加执行文件路径
import { open as dialogOpen } from '@tauri-apps/api/dialog';
const addlnk =async function(){
    console.log(1)
    const selected:any = await dialogOpen({
        multiple:false,
        filters:[{
            name:'程序路径',
            extensions:['exe','lnk','ps1']
        }] 
    });
    newlnk.value = selected
    console.log(selected)
}

// 选择添加图标
const addicon =async function(){
    console.log(1)
    let selected:any = await dialogOpen({
        filters:[{
            name:'图标路径', 
            extensions:['png','svg','jpg','jpeg']
        }]
    });
    // selected = convertFileSrc(selected);
    newicon.value = selected
    console.log(selected)
}

// 添加新lnk
const addnewlnk = function(){
    visible.value= false;
    if(newicon.value.length>1&&newlnk.value.length>1){
        lnkarr.push({
            img:convertFileSrc(newicon.value),
            exec:newlnk.value,
            program:newprogram.value
        });
        savelnk();
    }else{
    }
    newicon.value = ''
    newlnk.value = ''
    newprogram.value = ''
}
//#endregion

//#region storage

const savelnk = function(){
    localStorage.setItem("homelnk",JSON.stringify(lnkarr));
}

const getlnk = function(){
    let str:string|null = localStorage.getItem("homelnk");
    console.log(str)
    if(str){
        return JSON.parse(str);
    }else{

        let lnks =  [
            {
                img:'note/notepad.png',
                exec:'C:/Windows/notepad.exe',
                program:'记事本',
            },
            {
                img:'note/resource-manager.png',
                exec:'C:/Windows/explorer.exe',
                program:'资源管理器',
            },
            {
                img:'note/regedit.png',
                exec:'C:/Windows/regedit.exe',
                program:'注册表',
            },
            {
                img:'note/calc.png',
                exec:'C:/Windows/system32/calc.exe',
                program:'计算器',
            },
            {
                img:'note/cmd.png',
                exec:'C:/Windows/system32/cmd.exe',
                program:'CMD',
            },
            {
                img:'note/computer-configuration.png',
                exec:'C:/Windows/system32/compmgmt.msc',
                program:'计算机管理',
            },
            {
                img:'note/control-panel.png',
                exec:'C:/Windows/system32/control.exe',
                program:'控制面板',
            },
            {
                img:'note/disk.png',
                exec:'C:/Windows/system32/diskmgmt.msc',
                program:'磁盘管理',
            },
            {
                img:'note/Policy-Group.png',
                exec:'C:/Windows/system32/gpedit.msc',
                program:'本地策略组',
            },
            {
                img:'note/Computer-information.png',
                exec:'C:/Windows/system32/msinfo32.exe',
                program:'系统信息',
            },
            {
                img:'note/remote-desktop.png',
                exec:'C:/Windows/system32/mstsc.exe',
                program:'远程桌面',
            },
            {
                img:'note/keyboard.png',
                exec:'C:/Windows/system32/osk.exe',
                program:'屏幕键盘',
            },
            {
                img:'note/Volume.png',
                exec:'C:/Windows/system32/SndVol.exe',
                program:'音量合成器',
            },
            {
                img:'note/task-manager.png',
                exec:'C:/Windows/system32/Taskmgr.exe',
                program:'任务管理器',
            },
            {
                img:'note/firewall.png',
                exec:'C:/Windows/system32/WF.msc',
                program:'防火墙',
            },

        ]
        localStorage.setItem('homelnk',JSON.stringify(lnks));
        return lnks;
    }
    
}

onMounted(async ()=>{
    appWindow.setSkipTaskbar(false);
    appWindow.show();
    appWindow.setFocus();
    lnkarr.push(...getlnk());
})

//#endregion

///////////////////////////////////////创建窗口code///////////////////////////////////////////
//#region 创建folderlnk文件夹
import { WebviewWindow } from '@tauri-apps/api/window'
import { uuid } from '../function'
import { windowType } from '../types'
const visible2 = ref<boolean>(false);
const row = ref<number>(3);
const col = ref<number>(3);
const addwindows = function(){
    let label:string = 'folder-'+uuid();
    let strwins = localStorage.getItem('wins');
    if(strwins){
        let wins:string[] = JSON.parse(strwins);
        wins.push(label)
        localStorage.setItem('wins',JSON.stringify(wins));
    }else{
        localStorage.setItem('wins',JSON.stringify([label]));
    }
    // 创建新窗口
    new WebviewWindow(label,{
        title:"folder",
        width:(60*col.value+10*(col.value+1)),
        height:(60*row.value+10*(row.value+1)),
        decorations:false,
        transparent:true,
        fileDropEnabled:false,
        skipTaskbar:true,
        url:'/#/folder/'+row.value+'/'+col.value
    });
    // 创建窗口数据storage
    let winStorage:windowType = {
        position:{
            x:0,
            y:0,
        },
        label:label,
        width:(60*col.value+10*(col.value+1)),
        height:(60*row.value+10*(row.value+1)),
        alwaysOnTop:false,
        url:'/#/folder/'+row.value+'/'+col.value,
        fileDropEnabled:false,
    }
    localStorage.setItem(label,JSON.stringify(winStorage))

    visible2.value = false;
}

const add2 = function(){
    visible2.value = true;
}


//#endregion

//#region time
const opentime = function(){
    let label:string = 'time-'+uuid();
    let strwins = localStorage.getItem('wins');
    if(strwins){
        let wins:string[] = JSON.parse(strwins);
        wins.push(label)
        localStorage.setItem('wins',JSON.stringify(wins));
    }else{
        localStorage.setItem('wins',JSON.stringify([label]));
    }

    const win = new WebviewWindow(label,{
        title:"time",
        width:310,
        height:80,
        decorations:false,
        transparent:true,
        url:'/#/time',
        skipTaskbar:true,
    })

    // 创建窗口数据storage
    let winStorage:windowType = {
        position:{
            x:0,
            y:0,
        },
        label:label,
        width:310,
        height:80,
        alwaysOnTop:false,
        url:'/#/time',
        fileDropEnabled:true,
    }
    localStorage.setItem(label,JSON.stringify(winStorage))
}

//#endregion

//#region weather

const openweather = function(){
    let label:string = 'weather'+uuid();
    let strwins = localStorage.getItem('wins');
    if(strwins){
        let wins:string[] = JSON.parse(strwins);
        wins.push(label)
        localStorage.setItem('wins',JSON.stringify(wins));
    }else{
        localStorage.setItem('wins',JSON.stringify([label]));
    }
    const win = new WebviewWindow(label,{
        title:"weather",
        width:200,
        height:200,
        decorations:false,
        transparent:true,
        url:'/#/weather',
        skipTaskbar:true,
    })

    let winStorage:windowType = {
        position:{
            x:0,
            y:0,
        },
        label:label,
        width:200,
        height:200,
        alwaysOnTop:false,
        url:'/#/weather',
        fileDropEnabled:true,
    }
    localStorage.setItem(label,JSON.stringify(winStorage))
}

const opensearch = function(){
    let label:string = 'search-'+uuid();
    let strwins = localStorage.getItem('wins');
    if(strwins){
        let wins:string[] = JSON.parse(strwins);
        wins.push(label)
        localStorage.setItem('wins',JSON.stringify(wins));
    }else{
        localStorage.setItem('wins',JSON.stringify([label]));
    }
    const win = new WebviewWindow(label,{
        title:"search",
        width:200,
        height:200,
        decorations:false,
        transparent:true,
        url:'/#/search',
        skipTaskbar:true,
    })

    let winStorage:windowType = {
        position:{
            x:0,
            y:0,
        },
        label:label,
        width:60,
        height:60,
        alwaysOnTop:false,
        url:'/#/search',
        fileDropEnabled:true,
    }
    localStorage.setItem(label,JSON.stringify(winStorage))
}

const openStartMenu = function(){
    let label:string = 'startMenu-'+uuid();
    let strwins = localStorage.getItem('wins');
    if(strwins){
        let wins:string[] = JSON.parse(strwins);
        wins.push(label)
        localStorage.setItem('wins',JSON.stringify(wins));
    }else{
        localStorage.setItem('wins',JSON.stringify([label]));
    }
    const win = new WebviewWindow(label,{
        title:"startMenu",
        width:200,
        height:200,
        decorations:false,
        transparent:true,
        url:'/#/startMenu',
        skipTaskbar:true,
    })

    let winStorage:windowType = {
        position:{
            x:0,
            y:0,
        },
        label:label,
        width:200,
        height:200,
        alwaysOnTop:false,
        url:'/#/startMenu',
        fileDropEnabled:true,
    }
    localStorage.setItem(label,JSON.stringify(winStorage))
}

const openImage = function(){
    let label:string = 'image-'+uuid();
    let strwins = localStorage.getItem('wins');
    if(strwins){
        let wins:string[] = JSON.parse(strwins);
        wins.push(label)
        localStorage.setItem('wins',JSON.stringify(wins));
    }else{
        localStorage.setItem('wins',JSON.stringify([label]));
    }
    const win = new WebviewWindow(label,{
        title:"image",
        width:200,
        height:200,
        decorations:false,
        transparent:true,
        url:'/#/image',
        skipTaskbar:true,
    })

    let winStorage:windowType = {
        position:{
            x:0,
            y:0,
        },
        label:label,
        width:200,
        height:200,
        alwaysOnTop:false,
        url:'/#/image',
        fileDropEnabled:true,
    }
    localStorage.setItem(label,JSON.stringify(winStorage))
}

//#endregion


import { initWindow } from '../composables/common'
initWindow();
import { forbidSelect } from '../composables/common'
forbidSelect()
import { hideRightMenu } from '../function';
hideRightMenu();

appWindow.setResizable(false);


</script>

<template>
    <div class="home" @drop="$event.preventDefault()">
        <vue-Title>
            <template v-slot:left>
            </template>
            <template v-slot:default>
            </template>
            <template v-slot:right>
                <div @click="closeWindow" class="title-icon-div">
                    <img class="title-img-close" :src="'icon/close.png'" alt="">
                </div>
                <div @click="maxWindow" class="title-icon-div">
                    <img class="title-img-max" :src="'icon/max2.png'" alt="">
                </div>
                <div @click="miniWindow" class="title-icon-div">
                    <img class="title-img-minize" :src="'icon/minize2.png'" alt="">
                </div>
            </template>
        </vue-Title>
            <div class="menu" draggable="false" @dragover="dragover($event)" @drop="delbool = false">
                <div class="grid-div">
                    <div 
                    draggable="true" 
                    @dragstart="dragstart($event,index,item)" 
                    @dragover="dragover($event)" 
                    @drop="drop($event,index)" 
                    @click="execCommand(item.exec)"
                    v-for="(item,index) in lnkarr" 
                    :key="item.img" 
                    class="grid-item">
                        <img draggable="false" :src="item.img" class="grid-img" :alt="item.program">
                    </div>
                    <div 
                    v-show="delbool"
                    :draggable="true" 
                    class="grid-item" 
                    @click="delete" 
                    @dragover="dragover($event)" 
                    @drop="dragdelete($event)">
                        <img :draggable="true" :src="'note/garbage.png'" class="grid-img" >
                    </div>
                    <div :draggable="false" class="grid-item" @click="add">
                        <img :draggable="false" :src="'note/add2.png'" class="grid-img" >
                    </div>
                    <div :draggable="false" class="grid-item" @click="add2">
                        <img :draggable="false" :src="'note/folder.png'" class="grid-img" >
                    </div>
                    <div v-if="true" class="grid-item" @click="opentime">
                        <img :draggable="false" :src="'note/time.png'" class="grid-img" >
                    </div>
                    <div v-if="true" class="grid-item" @click="openweather">
                        <img :draggable="false" :src="'note/weather.png'" class="grid-img" >
                    </div>
                    <div v-if="true" class="grid-item" @click="opensearch">
                        <img :draggable="false" :src="'note/search.png'" class="grid-img" >
                    </div>
                    <div v-if="false" class="grid-item" @click="openStartMenu">
                        <img :draggable="false" :src="'note/startMenu.png'" class="grid-img" >
                    </div>
                    <div v-if="true" class="grid-item" @click="openImage">
                        <img :draggable="false" :src="'note/image.png'" class="grid-img" >
                    </div>
                </div>
            </div>
    </div>
    <!-- 添加lnk -->
    <tiny-dialog-box v-model:visible="visible" :show-close="false" width="80%" top="20%">
        <tiny-input class="input" readonly clearable placeholder="选择程序路径" v-model="newlnk" @click="addlnk"></tiny-input>
        <tiny-input class="input" readonly clearable placeholder="选择程序图标" v-model="newicon" @click="addicon"></tiny-input>
        <tiny-input class="input" placeholder="程序名称" v-model="newprogram"></tiny-input>
        <template #footer>
            <tiny-button type="primary" @click="addnewlnk"> 确定 </tiny-button>
            <tiny-button  @click="visible = false" > 取消 </tiny-button>
        </template>
    </tiny-dialog-box>

    <!-- 添加新folder -->
    <tiny-dialog-box v-model:visible="visible2" :show-close="false" width="60%" top="20%">
            <tiny-numeric style="width: 80%;margin:0 10%;" size="mini" width="20px" v-model="row" min="1" max="20" mouseWheel unit="行"></tiny-numeric>
            <tiny-numeric style="width: 80%;margin:0 10%;" size="mini" width="20px" v-model="col" min="1" max="20" mouseWheel unit="列"></tiny-numeric>
        <template #footer>
            <tiny-button type="primary" @click="addwindows"> 确定 </tiny-button>
            <tiny-button  @click="visible2 = false" > 取消 </tiny-button>
        </template>
    </tiny-dialog-box>
</template>

<style scoped>
/* dialog */

/* add */
.input{
    margin-bottom: 20px;
}

/* menu */

.menu::-webkit-scrollbar {
    display: none;
}

.menu {
    width: 100vw;
    height: calc(100vh - 30px);
    background: rgba(217,217,217,0.5);
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    padding: 5px 5px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    overflow-x: hidden;
    overflow-y: scroll;
}

.grid-div{
    /* width: auto; */
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: flex-start;
}
.grid-item{
    width: 60px;
    height: 60px;
    /* background: white; */
    border-radius: 50%;
    margin: 5px 5px;
    box-shadow: 0px 0px 15px 15px rgba(217,217,217,0.5) inset;
    /* box-shadow: 0px 0px 1px 1px rgba(0,0,0,0.5); */
}
.grid-img{
    width: 40px;
    height: 40px;
    margin: 10px;
    border-radius: 5px;
}
/* title */
html,body{
    width: 100vw;
    height: 100vh;
    border-radius: 5px;
    background: rgba(217,217,217,0);
}
.home {
    width: 100vw;
    height: 100vh;
}
.title-icon-div{
    float: right;
    width: 30px;
    height: 30px;
    text-align: center;
}
.title-icon-div:hover{
    background: rgba(217,217,217,255);
}
.title-img-minize{
    width: 18px;
    height: 18px;
    margin: 6px 0px;
}

.title-img-max{
    width: 16px;
    height: 16px;
    margin: 7px 0px;
}

.title-img-close{
    width: 18px;
    height: 18px;
    margin: 6px 0px;
}

</style>